<template>
  <el-container class="Notice">
    <el-main>
      <el-row v-for="item in initTags" :key="item.type" class="mt30">
        <el-col :span="24" class="flex">
          <span class="title fs18 mr10">{{ item.name }}列表</span>
          <Cbutton size="small" icon="el-icon-plus" @click.native="openDialog(item.type)">添加{{ item.name }}</Cbutton>
        </el-col>
        <el-col :span="24">
          <el-table
            v-loading="that[item.queryKey].loading"
            :data="that[item.dataKey]"
            class="mt20"
            style="width: 100%"
            border
          >
            <el-table-column prop="updateTime" label="创建时间" align="center">
              <template slot-scope="{row}">
                <span>{{ row.createTime | setTime }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="公告内容" show-overflow-tooltip align="center">
              <template slot-scope="{row}">
                <span v-if="!row.edit">{{ row.name | isNullData }}</span>
                <el-input
                  v-else
                  v-model="row.name"
                  type="textarea"
                  autosize
                  placeholder="请输入内容"
                />
              </template>
            </el-table-column>
            <el-table-column prop="type" label="公告类型" align="center">
              <template slot-scope="{row}">
                <el-tag v-if="row.type === 'system'" effect="plain">系统公告</el-tag>
                <el-tag v-if="row.type === 'shop'" effect="plain" type="success">店铺公告</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="是否使用" align="center">
              <template slot-scope="{row}">
                <el-switch
                  v-model="row.isShow"
                  active-text="使用"
                  inactive-text="关闭"
                  @change="(value) => { modifyNoticeSwitch(row) }"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="{row}">
                <el-button v-if="!row.edit" type="primary" icon="el-icon-edit" size="small" @click="row.edit = true">修 改</el-button>
                <el-button v-if="row.edit" type="info" icon="el-icon-close" size="small" @click="row.edit = false;row.name = row.originalName">取 消</el-button>
                <el-button v-if="row.edit" type="success" icon="el-icon-check" size="small" @click="messageModifyShow({ id: row.id, isShow: row.isShow, type: row.type, name: row.name}, row.type)">确 定</el-button>
                <el-popconfirm
                  title="确定要执行该操作吗？"
                  @confirm="removeNotice(row)"
                >
                  <el-button slot="reference" type="danger" icon="el-icon-delete" size="small" class="ml10">删 除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <Cpagination
            :total="that[item.queryKey].total"
            :page.sync="that[item.queryKey].page"
            :limit.sync="that[item.queryKey].size"
            class="mt10"
            @pagination="getList(item.queryKey, item.dataKey)"
          />
        </el-col>
      </el-row>
    </el-main>
    <Cdialog
      :visible="dialog.visible"
      :title="dialog.title"
      width="600px"
      class="Notice-dialog"
      @handleClose="handleClose"
    >
      <el-form :model="dialog" label-width="80px" label-position="left">
        <el-form-item label="公告内容">
          <el-input v-model="dialog.name" type="textarea" :autosize="{ minRows: 2 }" placeholder="请在此输入公告内容" />
        </el-form-item>
        <el-form-item label="是否使用">
          <el-switch
            v-model="dialog.isShow"
            active-text="使用"
            inactive-text="关闭"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="flexCenter">
        <el-button type="primary" size="small" @click="submitDialog">确 定</el-button>
        <el-button size="small" @click="handleClose">取 消</el-button>
      </div>
    </Cdialog>
  </el-container>
</template>
<script>
import {
  messageGetList,
  messageModifyShow,
  messageDelete
} from '@/api/message'
export default {
  data() {
    return {
      initTags: [ // 初始化用来循环创造两个类型的表格
        {
          name: '系统公告',
          type: 'system',
          queryKey: 'SystemlistQuery', // 分页数据key名
          dataKey: 'tableSystemData' // 表格数据key名
        },
        {
          name: '店铺公告',
          type: 'shop',
          queryKey: 'ShoplistQuery', // 分页数据key名
          dataKey: 'tableShopData' // 表格数据key名
        }
      ],
      SystemlistQuery: { // 分页数据
        page: 1,
        size: 10,
        total: 0,
        type: 'system',
        loading: true
      },
      ShoplistQuery: {
        page: 1,
        size: 10,
        total: 0,
        type: 'shop',
        loading: true
      },
      tableSystemData: [], // 系统公告数据
      tableShopData: [], // 店铺公告数据
      that: this,
      dialog: { // 弹窗数据
        title: '',
        visible: false,
        type: '',
        name: '',
        isShow: true
      }
    }
  },
  created() {
    this.getList('SystemlistQuery', 'tableSystemData')
    this.getList('ShoplistQuery', 'tableShopData')
  },
  methods: {
    // 提交弹窗
    async submitDialog() {
      if (!this.dialog.name) {
        this.$message.error('请输入公告内容')
        return
      }
      const res = await messageModifyShow({
        name: this.dialog.name,
        type: this.dialog.type,
        isShow: this.dialog.isShow
      })
      if (res.code === 0) {
        this.$message.success(res.msg)
        // 刷新数据
        if (this.dialog.type === 'system') this.getList('SystemlistQuery', 'tableSystemData')
        if (this.dialog.type === 'shop') this.getList('ShoplistQuery', 'tableShopData')
        this.handleClose()
      }
    },
    // 打开弹窗
    openDialog(type) {
      switch (type) {
        case 'system':
          this.dialog.title = '添加系统公告'
          break
        case 'shop':
          this.dialog.title = '添加店铺公告'
          break
      }
      this.dialog.visible = true
      this.dialog.type = type
      console.log(this.dialog)
    },
    // 关闭弹窗
    handleClose() {
      this.dialog = { // 弹窗数据
        title: '',
        visible: false,
        type: '',
        name: '',
        isShow: true
      }
    },
    // 删除单行
    async removeNotice(row) {
      const res = await messageDelete({ id: row.id })
      if (res.code === 0) {
        this.$message.success(res.msg)
        // 刷新数据
        if (row.type === 'system') this.getList('SystemlistQuery', 'tableSystemData')
        if (row.type === 'shop') this.getList('ShoplistQuery', 'tableShopData')
      }
    },
    // 修改单行开关
    modifyNoticeSwitch(row) {
      this.messageModifyShow({ // 开关操作 不传name参数
        id: row.id,
        isShow: row.isShow,
        type: row.type
      }, row.type)
    },
    // 更新公告内容或创建公告接口
    async messageModifyShow(data, type) {
      const res = await messageModifyShow(data)
      if (res.code === 0) {
        // if (type === 'system') this.getList('SystemlistQuery', 'tableSystemData')
        // if (type === 'shop') this.getList('ShoplistQuery', 'tableShopData')
        this.$message.success(res.msg)
        // 不访问接口来刷新数据（本地修改）
        if (data.id && data.name) { // 是修改操作并且修改内容才进行
          let dataKey = type === 'system' ? 'tableSystemData' : 'tableShopData'
          const index = this[dataKey].findIndex(item => item.id === data.id)
          this[dataKey][index].edit = false // 更新本地数据
          this[dataKey][index].originalName = data.name
        } else {
          if (type === 'system') this.getList('SystemlistQuery', 'tableSystemData')
          if (type === 'shop') this.getList('ShoplistQuery', 'tableShopData')
        }
      }
    },
    // 初始化
    async getList(queryKey, dataKey) {
      const res = await messageGetList(this[queryKey])
      if (res.code === 0) {
        const { data } = res
        data.list.forEach(item => {
          item['edit'] = false
          item['originalName'] = item.name
        })
        this[dataKey] = data.list
        this[queryKey].total = data.total
        this[queryKey].loading = false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.Notice{
  height: 100%;
  width: 100%;
}
.Notice-dialog{
  ::v-deep .el-form{
    padding: 10px;
  }
}
</style>
